package com.modebing.activiti7.config;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.impl.cfg.SpringBeanFactoryProxyMap;
import org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.activiti.engine.repository.Deployment;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Slf4j
@Configuration
public class ActivitiConfig {

    // 注入Spring上下文和数据源
    private final ApplicationContext applicationContext;
    private final DataSource dataSource;
    private final PlatformTransactionManager transactionManager;  // 新增事务管理器

    // 从配置文件注入参数
    @Value("${spring.activiti.database-schema-update}")
    private String databaseSchemaUpdate;
    @Value("${spring.activiti.async-executor-activate}")
    private boolean asyncExecutorActivate;

    // 构造函数注入必要的依赖（增加事务管理器）
    public ActivitiConfig(DataSource dataSource,
                          ApplicationContext applicationContext,
                          PlatformTransactionManager transactionManager) {  // 注入事务管理器
        this.dataSource = dataSource;
        this.applicationContext = applicationContext;
        this.transactionManager = transactionManager;  // 初始化事务管理器
    }


    @Bean
    public ProcessEngine processEngine() {
        // 关键修改：使用SpringProcessEngineConfiguration而非独立配置
        SpringProcessEngineConfiguration cfg = new SpringProcessEngineConfiguration();

        // 基础配置
        cfg.setDataSource(dataSource);
        cfg.setTransactionManager(transactionManager);  // 关联Spring事务管理器
        cfg.setDatabaseSchemaUpdate(databaseSchemaUpdate);
        cfg.setAsyncExecutorActivate(asyncExecutorActivate);

        // 核心配置：绑定Spring上下文，让Activiti能访问Spring管理的Bean
        cfg.setApplicationContext(applicationContext);

        // 可选：设置Bean解析器（增强Spring Bean的访问能力）
        cfg.setBeans(new SpringBeanFactoryProxyMap(applicationContext));

        // 构建流程引擎
        return cfg.buildProcessEngine();
    }

    @Bean
    public RepositoryService repositoryService() {
        return processEngine().getRepositoryService();
    }

    @Bean
    public RuntimeService runtimeService() {
        return processEngine().getRuntimeService();
    }

    @Bean
    public TaskService taskService() {
        return processEngine().getTaskService();
    }
    @Bean
    public HistoryService historyService() {
        return processEngine().getHistoryService();
    }
}
